/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 权限测试页面 - 用于测试权限管理功能
 */

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import '../services/permission_manager.dart';
import '../widgets/common/permission_guide_widget.dart';

/// 权限测试页面
class PermissionTestPage extends StatefulWidget {
  const PermissionTestPage({Key? key}) : super(key: key);

  @override
  State<PermissionTestPage> createState() => _PermissionTestPageState();
}

class _PermissionTestPageState extends State<PermissionTestPage> {
  Map<String, dynamic>? _permissionReport;
  bool _isLoading = false;
  String? _lastOperationResult;

  @override
  void initState() {
    super.initState();
    _refreshPermissionReport();
  }

  /// 刷新权限报告
  Future<void> _refreshPermissionReport() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final report = await PermissionManager.instance.getPermissionReport();
      if (mounted) {
        setState(() {
          _permissionReport = report;
          _isLoading = false;
        });
      }
    } catch (error) {
      debugPrint('PermissionTestPage: 获取权限报告失败 - $error');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  /// 请求所有权限
  Future<void> _requestAllPermissions() async {
    setState(() {
      _isLoading = true;
      _lastOperationResult = null;
    });

    try {
      final result = await PermissionManager.instance.requestAudioPermissions();
      if (mounted) {
        setState(() {
          _lastOperationResult = result ? '权限请求成功' : '部分权限被拒绝';
          _isLoading = false;
        });
        await _refreshPermissionReport();
      }
    } catch (error) {
      debugPrint('PermissionTestPage: 请求权限失败 - $error');
      if (mounted) {
        setState(() {
          _lastOperationResult = '权限请求失败: $error';
          _isLoading = false;
        });
      }
    }
  }

  /// 检查权限状态
  Future<void> _checkPermissions() async {
    setState(() {
      _isLoading = true;
      _lastOperationResult = null;
    });

    try {
      final hasPermissions =
          await PermissionManager.instance.checkPermissions();
      if (mounted) {
        setState(() {
          _lastOperationResult = hasPermissions ? '所有权限已授予' : '部分权限未授予';
          _isLoading = false;
        });
        await _refreshPermissionReport();
      }
    } catch (error) {
      debugPrint('PermissionTestPage: 检查权限失败 - $error');
      if (mounted) {
        setState(() {
          _lastOperationResult = '检查权限失败: $error';
          _isLoading = false;
        });
      }
    }
  }

  /// 打开应用设置
  Future<void> _openAppSettings() async {
    setState(() {
      _lastOperationResult = null;
    });

    try {
      final opened = await PermissionManager.instance.openSettings();
      if (mounted) {
        setState(() {
          _lastOperationResult = opened ? '已打开应用设置' : '无法打开应用设置';
        });
      }
    } catch (error) {
      debugPrint('PermissionTestPage: 打开应用设置失败 - $error');
      if (mounted) {
        setState(() {
          _lastOperationResult = '打开应用设置失败: $error';
        });
      }
    }
  }

  /// 显示权限引导对话框
  void _showPermissionGuide() {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        child: PermissionGuideWidget(
          title: '权限测试',
          description: '这是权限引导组件的测试',
          permissions: PermissionItems.audioPlaybackPermissions,
          onPermissionGranted: () {
            Navigator.of(context).pop();
            _refreshPermissionReport();
          },
          onPermissionDenied: () {
            Navigator.of(context).pop();
          },
        ),
      ),
    );
  }

  /// 请求特定权限
  Future<void> _requestSpecificPermission(Permission permission) async {
    setState(() {
      _isLoading = true;
      _lastOperationResult = null;
    });

    try {
      final result =
          await PermissionManager.instance.requestPermission(permission);
      if (mounted) {
        setState(() {
          _lastOperationResult = result
              ? '${permission.toString()} 权限请求成功'
              : '${permission.toString()} 权限被拒绝';
          _isLoading = false;
        });
        await _refreshPermissionReport();
      }
    } catch (error) {
      debugPrint('PermissionTestPage: 请求特定权限失败 - $error');
      if (mounted) {
        setState(() {
          _lastOperationResult = '请求权限失败: $error';
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('权限测试'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _refreshPermissionReport,
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 操作结果显示
                  if (_lastOperationResult != null) ...[
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: _lastOperationResult!.contains('成功') ||
                                _lastOperationResult!.contains('已授予')
                            ? Colors.green.withOpacity(0.1)
                            : Colors.orange.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(
                          color: _lastOperationResult!.contains('成功') ||
                                  _lastOperationResult!.contains('已授予')
                              ? Colors.green
                              : Colors.orange,
                        ),
                      ),
                      child: Text(
                        _lastOperationResult!,
                        style: TextStyle(
                          color: _lastOperationResult!.contains('成功') ||
                                  _lastOperationResult!.contains('已授予')
                              ? Colors.green[700]
                              : Colors.orange[700],
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                  ],

                  // 操作按钮区域
                  _buildActionSection(),
                  const SizedBox(height: 24),

                  // 权限报告区域
                  _buildPermissionReportSection(),
                ],
              ),
            ),
    );
  }

  /// 构建操作区域
  Widget _buildActionSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '权限操作',
              style: Theme.of(context).textTheme.titleLarge?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
            ),
            const SizedBox(height: 16),

            // 主要操作按钮
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                ElevatedButton.icon(
                  onPressed: _requestAllPermissions,
                  icon: const Icon(Icons.security),
                  label: const Text('请求所有权限'),
                ),
                ElevatedButton.icon(
                  onPressed: _checkPermissions,
                  icon: const Icon(Icons.check_circle),
                  label: const Text('检查权限状态'),
                ),
                ElevatedButton.icon(
                  onPressed: _openAppSettings,
                  icon: const Icon(Icons.settings),
                  label: const Text('打开应用设置'),
                ),
                ElevatedButton.icon(
                  onPressed: _showPermissionGuide,
                  icon: const Icon(Icons.help),
                  label: const Text('显示权限引导'),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // 特定权限操作
            Text(
              '特定权限操作',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w500,
                  ),
            ),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                OutlinedButton(
                  onPressed: () =>
                      _requestSpecificPermission(Permission.notification),
                  child: const Text('请求通知权限'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建权限报告区域
  Widget _buildPermissionReportSection() {
    if (_permissionReport == null) {
      return const Card(
        child: Padding(
          padding: EdgeInsets.all(16),
          child: Text('暂无权限报告'),
        ),
      );
    }

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(
                  '权限报告',
                  style: Theme.of(context).textTheme.titleLarge?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                ),
                const Spacer(),
                Text(
                  '平台: ${_permissionReport!['platform'] ?? 'Unknown'}',
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: Colors.grey[600],
                      ),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // 权限详情
            if (_permissionReport!['permissions'] != null) ...[
              ...(_permissionReport!['permissions'] as Map<String, dynamic>)
                  .entries
                  .map((entry) {
                final permissionInfo = entry.value as Map<String, dynamic>;
                final isGranted = permissionInfo['isGranted'] as bool? ?? false;

                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 4),
                  child: Row(
                    children: [
                      Icon(
                        isGranted ? Icons.check_circle : Icons.cancel,
                        color: isGranted ? Colors.green : Colors.red,
                        size: 20,
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              entry.key,
                              style:
                                  const TextStyle(fontWeight: FontWeight.w500),
                            ),
                            Text(
                              permissionInfo['statusDescription'] ?? 'Unknown',
                              style: TextStyle(
                                color: Colors.grey[600],
                                fontSize: 12,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                );
              }).toList(),
            ] else if (_permissionReport!['error'] != null) ...[
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.red.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Row(
                  children: [
                    const Icon(Icons.error, color: Colors.red),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Text(
                        '错误: ${_permissionReport!['error']}',
                        style: const TextStyle(color: Colors.red),
                      ),
                    ),
                  ],
                ),
              ),
            ],

            const SizedBox(height: 12),

            // 时间戳
            Text(
              '更新时间: ${_permissionReport!['timestamp'] ?? 'Unknown'}',
              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                    color: Colors.grey[600],
                  ),
            ),
          ],
        ),
      ),
    );
  }
}
